
//
//  ModifyUserInfoViewController.m
//  AppointmentForCar
//
//  Created by Herron on 2016/11/11.
//  Copyright © 2016年 Herron. All rights reserved.
//

#import "ModifyUserInfoViewController.h"
#import "CityListViewController.h"
#import "CameraTakeMamanger.h"
#import "CarBrandListViewController.h"
#import "IQActionSheetPickerView.h"
#import "QRCodeViewController.h"
#import "ProvinceListViewController.h"
#import "SeriesModel.h"

@interface ModifyUserInfoViewController ()<IQActionSheetPickerViewDelegate>

@property (weak, nonatomic) IBOutlet UILabel *phoneLabel;
@property (weak, nonatomic) IBOutlet UIImageView *avatarImageView;
@property (weak, nonatomic) IBOutlet UITextField *nicknameTextField;
@property (weak, nonatomic) IBOutlet UILabel *cityLabel;
@property (weak, nonatomic) IBOutlet UILabel *carBrandLabel;
@property (weak, nonatomic) IBOutlet UIButton *licensePlateBtn;
@property (weak, nonatomic) IBOutlet UITextField *licensePlateTextField;
@property (weak, nonatomic) IBOutlet UIImageView *licenseImageView;
@property (weak, nonatomic) IBOutlet UIImageView *driverLicImageView;

@property (nonatomic, copy) NSString *avatarUrl;            // 头像
@property (nonatomic, copy) NSString *licensePhotoUrl;      // 车牌
@property (nonatomic, copy) NSString *driverLicPhotoUrl;    // 驾照
@property (nonatomic, strong) CityModel *city;              // 市区id
@property (nonatomic, strong) SeriesModel *series;          // 车辆品牌
@property (nonatomic, copy) NSString *driverQrcode;         // 二维码

@end

@implementation ModifyUserInfoViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"完善资料";
    
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"保存" style:UIBarButtonItemStylePlain target:self action:@selector(saveClick:)];
    
    NSString *driverId = [UserAccountManager shareUserManager].user.driverId;
    [NetWork postNetWorkWithUrl:kURLDriverInfo parame:@{@"driverId":driverId} successBlock:^(NSDictionary *dic) {
        NSLog(@"司机信息dic = %@", dic);
        NSDictionary *driverDic = dic[@"data"];
        UserModel *user = [UserModel mj_objectWithKeyValues:driverDic];
        NSLog(@"user = %@", user);
        self.driverQrcode = user.driverQrcode;
        self.phoneLabel.text = user.driverPhoneNumber;
        self.nicknameTextField.text = user.driverNickName;
        self.avatarImageView.urlPath = user.driverAvatarUrl;
        self.cityLabel.text = user.driverAddress;
        NSString *license = user.licensePlate;
        NSRange range = [license rangeOfString:@" "];
        NSString *subLicense1 = [license substringToIndex:range.location];
        NSString *subLicense2 = [license substringFromIndex:range.location];
        [self.licensePlateBtn setTitle:subLicense1 forState:UIControlStateNormal];
        self.licensePlateTextField.text = subLicense2;
        self.carBrandLabel.text = user.carModel;
        NSURL *licenseUrl = [NSURL URLWithString:[NSString stringWithFormat:@"%@/%@", kRootImageUrl, user.licensePhotoUrl]];
        [self.licenseImageView sd_setImageWithURL:licenseUrl];
        NSURL *driverLicUrl = [NSURL URLWithString:[NSString stringWithFormat:@"%@/%@", kRootImageUrl, user.driverLicPhotoUrl]];
        [self.driverLicImageView sd_setImageWithURL:driverLicUrl];
    } errorBlock:^(id error) {
        [HUDManager showWarningWithText:@"网络异常"];
    }];
    
    NSNotificationCenter *notification = [NSNotificationCenter defaultCenter];
    [notification addObserver:self selector:@selector(selectCity:) name:@"sendCityTwo" object:nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(reloadBrand:) name:@"sendBrand" object:nil];

}

- (void)viewWillAppear:(BOOL)animated {
    self.navigationController.navigationBar.translucent = NO;
    self.navigationController.navigationBar.hidden = NO;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}

#pragma mark - <CityListViewControllerDelegate>
- (void)selectCity:(NSNotification *)notification {
    NSDictionary *dic = notification.userInfo;
    CityModel *city = [[CityModel alloc] initWithDictionary:dic error:nil];
    self.cityLabel.text = city.name;
    self.city = city;
}

#pragma mark - <IQActionSheetPickerViewDelegate>
-(void)actionSheetPickerView:(IQActionSheetPickerView *)pickerView didSelectTitles:(NSArray *)titles {
    [self.licensePlateBtn setTitle:[titles componentsJoinedByString:@""] forState:UIControlStateNormal];
}


#pragma mark - event mothed
// 保存
- (void)saveClick:(id)sender {
    if (self.avatarUrl.length) {
        [NetWork postNetWorkWithUrl:kURLChangeAvatar parame:@{@"driverAvatarUrl":self.avatarUrl} successBlock:^(NSDictionary *json) {
            [UserAccountManager shareUserManager].user.driverAvatarUrl = self.avatarUrl;
            // 通知
            NSNotificationCenter *center = [NSNotificationCenter defaultCenter];
            [center postNotificationName:kNoticeChangeAvatarImage object:nil userInfo:json];
        } errorBlock:^(id error) {
            [HUDManager showWarningWithText:@"修改头像失败"];
        }];
    }
    if (self.nicknameTextField.text.length) {
        [NetWork postNetWorkWithUrl:kURLChangeNickName parame:@{@"driverNickName":self.nicknameTextField.text} successBlock:^(NSDictionary *dic) {
            NSLog(@"昵称dic = %@", dic);
            [UserAccountManager shareUserManager].user.driverNickName = self.nicknameTextField.text;
            // 通知
            NSNotificationCenter *center = [NSNotificationCenter defaultCenter];
            [center postNotificationName:kNoticeChangeName object:nil userInfo:dic];

        } errorBlock:^(id error) {
            [HUDManager showWarningWithText:@"修改昵称失败"];
        }];
    }
    if (self.city.cityId.length) {
        NSString *driverId = [UserAccountManager shareUserManager].user.driverId;
        [NetWork postNetWorkWithUrl:kURLChangeAddress parame:@{@"id":driverId, @"type":@"2", @"cityId":self.city.cityId} successBlock:^(NSDictionary *dic) {
            NSLog(@"修改地区dic = %@", dic);
        } errorBlock:^(id error) {
            [HUDManager showWarningWithText:@"修改地区失败"];
        }];
    }
    if (self.series) {
        [NetWork postNetWorkWithUrl:kURLChangeCarBrand parame:@{@"seriesId":self.series.seriesId} successBlock:^(NSDictionary *dic) {
        } errorBlock:^(id error) {
            [HUDManager showWarningWithText:@"修改品牌失败"];
        }];
    }
    if (self.licensePlateBtn.currentTitle.length) {
        NSString *plateNumber = [NSString stringWithFormat:@"%@ %@", self.licensePlateBtn.currentTitle, self.licensePlateTextField.text];
        [NetWork postNetWorkWithUrl:kURLChangePlateNumber parame:@{@"plateNumber":plateNumber} successBlock:^(NSDictionary *dic) {
            NSLog(@"车牌号dic = %@", dic);
        } errorBlock:^(id error) {
            [HUDManager showWarningWithText:@"修改车牌号码失败"];
        }];
    }
    if (self.licensePhotoUrl.length) {
        [NetWork postNetWorkWithUrl:kURLChangeLicensePhoto parame:@{@"licensePhotoUrl":self.licensePhotoUrl} successBlock:^(NSDictionary *dic) {
        } errorBlock:^(id error) {
            [HUDManager showWarningWithText:@"修改车牌照片失败"];
        }];
    }
    if (self.driverLicPhotoUrl.length) {
        [NetWork postNetWorkWithUrl:kURLChangeDriverLicensePhoto parame:@{@"driverLicPhotoUrl":self.driverLicPhotoUrl} successBlock:^(NSDictionary *dic) {
        } errorBlock:^(id error) {
            [HUDManager showWarningWithText:@"修改驾驶证照片失败"];
        }];
    }
    [self.navigationController popViewControllerAnimated:YES];
}


// 头像
- (IBAction)uploadAvatarClick:(id)sender {
    [[CameraTakeMamanger sharedInstance] cameraSheetInController:self handler:^(UIImage *image, NSString *imagePath) {
        NSLog(@"imagePath = %@", imagePath);
        [NetWork uploadImageWithUrl:kURLUploadImage image:image imageName:@"avatar" successBlock:^(NSDictionary *dic) {
            NSLog(@"dic = %@", dic);
            NSArray *urls = dic[@"data"][@"urls"];
            self.avatarUrl = [urls firstObject];
            [self.avatarImageView sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/%@", kRootImageUrl, self.avatarUrl]] placeholderImage:[UIImage imageNamed:@"registerAvatar"]];
        } errorBlock:^(id error) {
            [HUDManager showWarningWithText:@"上传失败"];
        }];
    }];
}

// 地区
- (IBAction)cityClick:(id)sender {
    ProvinceListViewController *vc = [[ProvinceListViewController alloc] init];
    vc.type = @"2";
    [self.navigationController pushViewController:vc animated:YES];
}

// 车辆品牌
- (IBAction)carBrandClick:(id)sender {
    CarBrandListViewController *vc = [[CarBrandListViewController alloc] init];
    vc.type = @"2";
    [self.navigationController pushViewController:vc animated:YES];
}

// 这牌类型
- (IBAction)licensePlateClick:(id)sender {
    IQActionSheetPickerView *picker = [[IQActionSheetPickerView alloc] initWithTitle:@"车牌号码" delegate:self];
    [picker setTag:2];
    [picker setTitlesForComponents:@[@[@"京",@"津",@"沪",@"渝",@"冀",@"豫",@"云",@"辽",@"黑",@"湘",@"皖",@"鲁",@"新",@"苏",@"浙",@"赣",@"桂",@"甘",@"晋",@"蒙",@"陕",@"吉",@"闽",@"贵",@"粤",@"青",@"藏",@"琼"],
                                     @[@"A",@"B",@"C",@"D",@"E",@"F",@"G",@"H",@"I",@"J",@"K",@"L",@"M",@"N",@"O",@"P",@"Q",@"R",@"S",@"T",@"U", @"V",@"W",@"X",@"Y",@"Z"]]];
    [picker show];
}

// 车牌照片
- (IBAction)uploadLicensePhotoClick:(id)sender {
    [[CameraTakeMamanger sharedInstance] cameraSheetInController:self handler:^(UIImage *image, NSString *imagePath) {
        [NetWork uploadImageWithUrl:kURLUploadImage image:image imageName:@"license" successBlock:^(NSDictionary *dic) {
            NSLog(@"dic = %@", dic);
            NSArray *urls = dic[@"data"][@"urls"];
            self.licensePhotoUrl = [urls firstObject];
            [self.licenseImageView sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/%@", kRootImageUrl, self.licensePhotoUrl]] placeholderImage:[UIImage imageNamed:@"example0"]];
        } errorBlock:^(id error) {
            [HUDManager showWarningWithText:@"上传失败"];
        }];
    }];
}

// 驾驶证照片
- (IBAction)uploadDriverLicPhotoClick:(id)sender {
    [[CameraTakeMamanger sharedInstance] cameraSheetInController:self handler:^(UIImage *image, NSString *imagePath) {
        NSLog(@"imagePath = %@", imagePath);
        [NetWork uploadImageWithUrl:kURLUploadImage image:image imageName:@"driverLic" successBlock:^(NSDictionary *dic) {
            NSLog(@"dic = %@", dic);
            NSArray *urls = dic[@"data"][@"urls"];
            self.driverLicPhotoUrl = [urls firstObject];
            [self.driverLicImageView sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/%@", kRootImageUrl, self.driverLicPhotoUrl]] placeholderImage:[UIImage imageNamed:@"example"]];
        } errorBlock:^(id error) {
            [HUDManager showWarningWithText:@"上传失败"];
        }];
    }];
}

- (IBAction)qrCodeClick:(id)sender {
    QRCodeViewController *vc = [[QRCodeViewController alloc] init];
    vc.code = self.driverQrcode;
    [self.navigationController pushViewController:vc animated:YES];
}

- (void)reloadBrand:(NSNotification *)notification {
    NSDictionary *dic = notification.userInfo;
    self.series = dic[@"brand"];
    self.carBrandLabel.text = self.series.name;
}

@end
